﻿using Authority.Model;
using Common.Library;
using Dapper.Library;
using Dapper.MsSql.Library;
using Dapper.Library.DataAccessSql;
using Network.Library;
using Redis.Library;
using System.Collections.Generic;
using System.Linq;
using Tool.Model;
using Container.Library;

namespace Authority.Logic
{
    /// <summary>
    /// 按钮功能管理逻辑类
    /// </summary>
    public class SysButtonServiceImpl : ISysButtonService
    {

        /// <summary>
        /// 分页获取所有的可操作按钮
        /// </summary>
        /// <param name="parametersInfo"></param>
        /// <returns></returns>
        public ResultJsonInfo<List<SysButtonEntity>> LoadSysButtonList(ParametersInfo<string> inputInfo)
        {
            var resultInfo = new ResultJsonInfo<List<SysButtonEntity>>();

            //using (var con = MySqlDataBase.GetConnection(DatabaseName.AuthorityDB_MySql))
            using (var con = MsSqlDataBase.GetConnection(DatabaseName.AuthorityDB_MsSql))
            {
                var result = con.QuerySet<SysButtonEntity>().WithNoLock()
                    .AndWhere(p => p.bIsDeleted == false);

                if (inputInfo.parameters.IsNotNullOrEmpty())
                {
                    result = result.AndWhere(p => p.sName.Contains(inputInfo.parameters));
                }

                var listInfo = result.OrderBy(inputInfo.order == "asc" ? OrderByType.Asc : OrderByType.Desc, inputInfo.field)
                    .PageList(inputInfo.page, inputInfo.limit);

                if (listInfo.Data.IsNotNull())
                {
                    resultInfo.Code = ActionCodes.Success;
                    resultInfo.Data = listInfo.Data.ToList();
                    resultInfo.Count = listInfo.Total;
                }
                else
                {
                    resultInfo.Msg = "无对应信息！";
                }
            }
            return resultInfo;
        }

        /// <summary>
        /// 根据Code获取操作按钮
        /// </summary>
        /// <returns></returns>
        public ResultJsonInfo<int> Save(ButtonsOperateRequest inputInfo)
        {

            var resultInfo = new ResultJsonInfo<int>();

            //using (var con = MySqlDataBase.GetConnection(DatabaseName.AuthorityDB_MySql))
            using (var con = MsSqlDataBase.GetConnection(DatabaseName.AuthorityDB_MsSql))
            {
                var result = 0;

                var sysButton = inputInfo.MapTo<SysButtonEntity>();
                sysButton.sHtml = $"<a class='layui-btn  {sysButton.sClass}' id='{sysButton.sId}'><i class='layui-icon {sysButton.sIcon}'></i>{sysButton.sName}</a>";
                sysButton.sHtmlXs = $"<a class='layui-btn  layui-btn-xs  {sysButton.sClass}'  lay-event='{sysButton.sId}'><i class='layui-icon {sysButton.sIcon}'></i>{sysButton.sName}</a>";

                if (inputInfo.gCode.IsNotNullOrEmpty())
                {
                    result = con.CommandSet<SysButtonEntity>()
                        .IfNotExists(p => p.gCode != inputInfo.gCode && (p.sId == sysButton.sId))
                        .Update(sysButton);
                }
                else
                {
                    sysButton.gCode = GuidHelper.GetGuid();
                    result = con.CommandSet<SysButtonEntity>()
                        .IfNotExists(p => p.sId == sysButton.sId)
                        .Insert(sysButton);
                }
                if (result > 0)
                {
                    resultInfo.Code = ActionCodes.Success;
                    resultInfo.Data = result;
                    resultInfo.Msg = "操作成功！";
                }
                else
                {
                    resultInfo.Msg = "操作失败,请检查ID是否重复！";
                }
            }
            return resultInfo;
        }

        /// <summary>
        /// 删除信息
        /// </summary>
        /// <param name="gCodeList"></param>
        /// <returns></returns>
        public ResultJsonInfo<int> Remove(List<string> gCodeList)
        {
            var resultInfo = new ResultJsonInfo<int>();
            //using (var con = MySqlDataBase.GetConnection(DatabaseName.AuthorityDB_MySql))
            using (var con = MsSqlDataBase.GetConnection(DatabaseName.AuthorityDB_MsSql))
            {
                var result = 0;

                if (gCodeList.Count >= 0)
                {

                    var exists = con.QuerySet<SysMenuButtonEntity>().AndWhere(p => gCodeList.Contains(p.gButtonCode)).Exists();
                    if (!exists)
                    {
                        result = con.CommandSet<SysButtonEntity>()
                          .AndWhere(a => gCodeList.Contains(a.gCode))
                          .UpdateByExp(p => new SysButtonEntity { bIsDeleted = true });

                        if (result > 0)
                        {
                            resultInfo.Code = ActionCodes.Success;
                            resultInfo.Data = result;
                            resultInfo.Msg = "操作成功！";
                        }
                        else
                        {
                            resultInfo.Msg = "操作失败！";
                        }
                    }
                    else
                    {
                        resultInfo.Msg = "选中按钮已被菜单使用，无法删除！";
                    }
                }
                else
                {
                    resultInfo.Msg = "ID为空，操作失败！";
                }
            }
            return resultInfo;
        }

        /// <summary>
        /// 保存当前用所拥有的按钮权限到Redis
        /// </summary>
        /// <param name="roleCodes"></param>
        public void AddButtonsCacheToRedis(string roleCodes)
        {
            List<SysUserRoleButtonsInfo> userRoleButtonsInfo = new List<SysUserRoleButtonsInfo>();
            var loginUser = UserSession.GetLoginUser<SysUserInfo>();

            if (roleCodes.IsNotNullOrEmpty())
            {
                List<string> listRoleCodes = roleCodes.Split(',').ToList();
                using (var con = MsSqlDataBase.GetConnection(DatabaseName.AuthorityDB_MsSql))
                {
                    var listInfo = con.QuerySet<View_SysUserRoleButtonsEntity>().AndWhere(p => listRoleCodes.Contains(p.gRoleCode)).Multiple();
                    userRoleButtonsInfo = listInfo.MapToList<SysUserRoleButtonsInfo>().Distinct().ToList();
                }
            }

            //可操作按钮，放redis中
            RedisClient.GetRedisDb(ConstRedisKey.RedisDbWeb)
               .HashSet<List<SysUserRoleButtonsInfo>>(ConstRedisKey.RedisButtonsCode, loginUser.LoginName, userRoleButtonsInfo);
        }
           
        /// <summary>
        /// 获取Redis中的按钮权限
        /// </summary>
        /// <returns></returns>
        public ResultJsonInfo<SysUserRoleButtonsHtmlInfo> LoadButtonsCacheFromRedis(string path)
        {
            var resultInfo = new ResultJsonInfo<SysUserRoleButtonsHtmlInfo>();

            var loginUser = UserSession.GetLoginUser<SysUserInfo>();

            //可操作按钮
            var info = RedisClient.GetRedisDb(ConstRedisKey.RedisDbWeb)
                .HashGet<List<SysUserRoleButtonsInfo>>(ConstRedisKey.RedisButtonsCode, loginUser.LoginName);

            //可操作菜单
            var sysMenuList = RedisClient.GetRedisDb(ConstRedisKey.RedisDbWeb)
                .HashGet<List<SysMenuEntity>>(ConstRedisKey.RedisMenusCode, loginUser.LoginName);

            //获取当前菜单编码
            string gMenuCode = sysMenuList.Find(p => p.sUrl == path).gCode;

            if (gMenuCode.IsNotNullOrEmpty())
            {
                //过滤出当前菜单可操作按钮
                var buttonsInfo = info.FindAll(p => p.gMenuCode == gMenuCode).OrderBy(p => p.iSort).ToList();

                if (buttonsInfo.Count > 0)
                {
                    SysUserRoleButtonsHtmlInfo htmlInfo = new SysUserRoleButtonsHtmlInfo();
                    foreach (var item in buttonsInfo)
                    {
                        if (item.iType == (int)ButtonType.Ordinary || item.iType == (int)ButtonType.AllHave)
                        {
                            htmlInfo.sHtml += " " + item.sHtml;
                        }
                        if (item.iType == (int)ButtonType.Small || item.iType == (int)ButtonType.AllHave)
                        {
                            if (string.IsNullOrEmpty(item.sMinBtnRemark))
                            {
                                htmlInfo.sHtmlXs += " " + item.sHtmlXs;
                            }
                            else
                            {
                                htmlInfo.sHtmlXs += " " + item.sMinBtnRemark;
                            }
                        }
                    }
                    resultInfo.Code = ActionCodes.Success;
                    resultInfo.Data = htmlInfo;
                    resultInfo.Msg = "操作成功！";
                }
                else
                {
                    resultInfo.Msg = "无可操作按钮！";
                }
            }
            else
            {
                resultInfo.Msg = "无该菜单操作权限！";
            }
            return resultInfo;
        }
    }
}
